package org.crud4j.validator;

import java.lang.reflect.Field;

class FieldValidator<T> implements BeanValidator<T> {

	private Field field;

	protected String name;

	protected ValueValidator valueValidator;

	@SuppressWarnings("unchecked")
	public FieldValidator(Field field, ValueValidator validator) {
		super();
		this.field = field;
		this.name = field.getName();
		this.field.setAccessible(true);
		this.valueValidator = validator;
	}

	public void validate(T bean) throws BeanValidatorException {
		try {
			Object value = this.field.get(bean);
			this.valueValidator.validate(value);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (ValueValidatorException e) {
			throw new BeanValidatorException(bean, new ValidationResult(
					this.name, e));
		}
	}

}
